package com.example.stock;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class stocklistActivity extends AppCompatActivity {

    private ListView lv;
    private ArrayList<stockitem> stockitemlist;
    private MyDatabaseHelper  dbHelper;
    private SQLiteDatabase db;
    private int id;
    private String stockname;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stocklist);
        dbHelper = new MyDatabaseHelper( this, getExternalFilesDir(null)+"/glodStore.db", null, 1);
        db=dbHelper.getWritableDatabase();
        stockitemlist= new ArrayList<stockitem>();

        Bundle bundle=getIntent().getExtras();
        stockname=bundle.getString("name");
        revw_data();
    }
    protected void revw_data(){//更新列表视图数据
        stockitemlist.clear();
        Cursor cursor = db.rawQuery("select id,number,buyprice,buyfee,sellprice,profit from stock where name='"+stockname+"' order by sellprice ASC,buyprice ASC",null);
        while(cursor.moveToNext()){
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            float buyprice = cursor.getFloat(cursor.getColumnIndex("buyprice"));
            float buyfee = cursor.getFloat(cursor.getColumnIndex("buyfee"));
            int num = cursor.getInt(cursor.getColumnIndex("number"));
            float sellprice = cursor.getFloat(cursor.getColumnIndex("sellprice"));
            float profit = cursor.getFloat(cursor.getColumnIndex("profit"));
            float cost=(buyprice*num*1.001f+buyfee*2.0f)/num;
            cost=Math.round(cost*100)/100.0f;
            stockitem st = new stockitem(id,sellprice,buyprice,buyfee,Float.toString(cost),Float.toString(profit),Integer.toString(num));
            stockitemlist.add(st);
        }
        cursor=db.rawQuery("select sum(profit) as profit from stock where name='"+stockname+"'",null);
        cursor.moveToFirst();
        float sum=cursor.getFloat(0);
        sum=Math.round(sum*100)/100.0f;//保留两位小数
        this.setTitle(stockname+",盈:"+Float.toString(sum)+'元');
        lv = (ListView)findViewById(R.id.stockList);

        lv.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return stockitemlist.size();
            }
            @Override
            public Object getItem(int position) {
                // return holdstocklist.get(position);
                return null;
            }
            @Override
            public long getItemId(int position) {

                // return position;
                return 0;
            }
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view ;
                if(convertView == null )
                {
                    LayoutInflater inflater = stocklistActivity.this.getLayoutInflater();
                    view = inflater.inflate(R.layout.stock_item,null);
                    //view = View.inflate(getBaseContext(),R.layout.item,null);
                }
                else
                {
                    view = convertView;
                }
                //从studentlist中取出一行数据，position相当于数组下标,可以实现逐行取数据
                stockitem st = stockitemlist.get(position);
                final stockitem inst=st;
                TextView msg = (TextView)view.findViewById(R.id.stockitem_msg);
                Button btn=(Button)view.findViewById(R.id.SellBtn);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v)
                    {
                        SellDialog dialog = new SellDialog(stocklistActivity.this, new SellDialog.OnEditInputFinishedListener(){
                            public void editInputFinished(float sellprice,float buyprice,float buyfee,int num,int id) {
                                float sellfee=(sellprice*num*0.0003f>5)?sellprice*num*0.0003f:5.0f;
                                float selltax=sellprice*num*0.001f;
                                float profit=(sellprice-buyprice)*num-buyfee-sellfee-selltax;
                                sellfee=Math.round(sellfee*100)/100.0f;
                                selltax=Math.round(selltax*100)/100.0f;
                                profit=Math.round(profit*100)/100.0f;
                                String strfee=Float.toString(sellfee);
                                String strtax=Float.toString(selltax);
                                String strfit=Float.toString(profit);
                                String strsell=Float.toString(sellprice);
                                String sql="update stock set sellprice="+strsell+",sellfee="+strfee+",selltax="+strtax+",profit="+strfit+",selldate=datetime(CURRENT_TIMESTAMP,'localtime') where id="+Integer.toString(id);
                                db.execSQL(sql);
                                lv.setAdapter(null);
                                lv.removeAllViewsInLayout();
                                revw_data();
                            }
                        },inst.cost,inst.id,inst.num,inst.buyprice,inst.buyfee);
                        dialog.setView(new EditText(stocklistActivity.this));  //若对话框无法弹出输入法，加上这句话
                        //dialog.setTitle(title);
                        dialog.show();
                    }
                });

                String msgout;
                if(st.sellprice>0.01f) {
                    msgout = st.num +"股,b" +Float.toString(st.buyprice)+"s"+Float.toString(st.sellprice)+ ",盈" + st.profit;
                    btn.setVisibility(View.GONE);
                    Button delbtn=(Button)view.findViewById(R.id.delBtn);
                    delbtn.setVisibility(View.VISIBLE);
                    final String strid=Integer.toString(st.id);
                    delbtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v)
                        {
                            AlertDialog.Builder builder  = new AlertDialog.Builder(stocklistActivity.this);
                            builder.setTitle("删除提示" ) ;
                            builder.setMessage("是否确认删除？" ) ;
                            builder.setPositiveButton("是",new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    String sql="DELETE FROM stock where id="+strid;
                                    db.execSQL(sql);
                                    lv.setAdapter(null);
                                    lv.removeAllViewsInLayout();
                                    revw_data();
                                }
                            } );
                            builder.setNegativeButton("否", null);
                            builder.show();
                        }
                    });
                }
                else {
                    btn.setVisibility(View.VISIBLE);
                    Button delbtn1=(Button)view.findViewById(R.id.delBtn);
                    delbtn1.setVisibility(View.GONE);
                    msgout = st.num +"股,买" +Float.toString(st.buyprice)+ ",本:" + st.cost + "元";
                }
                msg.setText(msgout);
                return view;
            }
        });/**/
    }
}
